package com.collection.common.base;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.UUID;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;

/**
 * 资源处理工具
 * 
 * @author 冯勇
 * 
 */
public class ResourceUtil {

	private static Logger logger = Logger.getLogger(ResourceUtil.class);

	private static Properties props = new Properties();
	private static String classPath;
	private static String appAbsolutePath;
	private static boolean isWindows;

	static {
		initialize();
	}

	public static void initialize() {
		String osType = System.getProperty("os.name");
		isWindows = osType == null
				|| osType.toUpperCase().indexOf("WINDOWS") > -1;
		if (isWindows) {
			classPath = ResourceUtil.class.getResource("/").getPath();
			classPath = classPath.replace("file:", "");
			int pos = classPath.indexOf("/classes/");
			if (pos > -1)
				classPath = classPath.substring(1, pos + 9);
		} else {
			classPath = ResourceUtil.class.getResource("").getPath();
			classPath = classPath.replace("file:", "");
			int pos = classPath.indexOf("/classes/");
			if (pos == -1) {
				pos = classPath.indexOf("/lib/");
				if (pos > -1)
					classPath = classPath.substring(0, pos + 5);
			} else {
				classPath = classPath.substring(0, pos + 9);
			}
		}
		classPath = classPath.replaceAll("/lib/", "/classes/");

		appAbsolutePath = classPath.replaceAll("/WEB-INF/classes/", "");
		// appRoot =
		// appAbsolutePath.substring(appAbsolutePath.lastIndexOf("/"));
		try {
			classPath = java.net.URLDecoder.decode(classPath, "UTF-8");
		} catch (Exception e) {
			// do nothing
		}

		loadProperties(classPath + "application.properties");
	}

	private static void loadProperties(String propertyFile) {
		InputStream ins = null;
		try {
			ins = new FileInputStream(propertyFile);
			props.load(ins);
			ins.close();
		} catch (Exception e) {
			logger.error("Can't found system config file: " + propertyFile
					+ ", please check." + e);
		} finally {
			try {
				if (ins != null)
					ins.close();
			} catch (IOException e) {
				// do nothing
			}
		}
	}

	public static String getAppAbsolutePath() {
		return appAbsolutePath;
	}

	/**
	 * 上传文件
	 * 
	 * @param savePath
	 * @param type
	 * @param file
	 * @param fileName
	 * @return
	 */
	public static String uploadFile(String savePath, String type, File file,
			String fileName) {
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;

		if (StringUtils.isNotBlank(fileName)) {
			fileName = UUID.randomUUID().toString()
					+ fileName.substring(fileName.lastIndexOf("."));
		}
		String descPath = savePath + "/upload/" + type;
		String filePath = descPath + "/" + fileName;
		File folder = new File(descPath);
		if (!folder.exists() && !folder.mkdirs()) {
			logger.error("目录不存，且无法创建该目录：" + descPath);
			return null;
		}
		try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(new FileOutputStream(filePath));
			byte[] buff = new byte[8192];
			int i;
			while ((i = bis.read(buff)) != -1)
				bos.write(buff, 0, i);
			bos.flush();

			System.out.println("/upload/" + type + "/" + fileName);
			return "/upload/" + type + "/" + fileName;
		} catch (IOException e) {
			logger.error("Save file failed: " + e);
			return null;
		} finally {
			try {
				if (bos != null)
					bos.close();
				if (bis != null)
					bis.close();
			} catch (IOException e) {
				// do nothing
			}
		}
	}

	public static boolean urlExists(String URLName) {
		// 设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。

		HttpURLConnection.setFollowRedirects(false);
		// 到 URL 所引用的远程对象的连接

		HttpURLConnection con = null;
		try {
			URL url = new URL(URLName);
			// String hostName = url.getHost();
			// System.out.println(hostName);
			// url = new URL(URLName.replace(hostName, "192.168.0.229"));
			// System.out.println(url + "--" + url.getHost());
			// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
			// "192.168.0.229", 80));
			con = (HttpURLConnection) url.openConnection();
			/*
			 * 设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE
			 * 以上方法之一是合法的，具体取决于协议的限制。
			 */
			con.setRequestMethod("HEAD");
			// con.setRequestProperty("Host", url.getHost());
			// 从 HTTP 响应消息获取状态码
			return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static String getProperty(String key, String defaultProperty) {
		return props.getProperty(key, defaultProperty);
	}

	public static String getProperty(String key) {
		return props.getProperty(key);
	}
}
